package com.spa.interfaces.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.spa.application.service.member.MemberOrderApplicationService;
import com.spa.domain.entity.*;
import com.spa.domain.service.*;
import com.spa.infrastructure.common.ResponseMessage;
import com.spa.infrastructure.repository.condition.CitiesServedCondition;
import com.spa.infrastructure.repository.condition.OrderInfoCondition;
import com.spa.infrastructure.repository.condition.OrderTransferCondition;
import com.spa.infrastructure.repository.service.RuleRepositoryService;
import com.spa.infrastructure.util.OrderUtils;
import com.spa.interfaces.BaseController;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;

@RestController
@Slf4j
public class DemoController extends BaseController {

    @Resource
    private MassagistService massagistService;

    @Resource
    private ShopService shopService;
    @Resource
    private RuleRepositoryService ruleRepositoryService;

    @Resource
    private OrderService orderService;

    @Resource
    private CitiesServedService citiesServedService;

    @Resource
    private ProfitService profitService;

    @Resource
    private OrderTransferService orderTransferService;

    @Resource
    private MemberOrderApplicationService memberOrderApplicationService;

    @PostMapping("/list4GroupByOrderLimitOne")
    public ResponseMessage<Massagist> test() throws Exception {
        OrderTransferCondition orderTransferCondition = new OrderTransferCondition();
        orderTransferCondition.setShopId(1765934485363798018L);
        orderTransferCondition.setHandleMark(1);
        orderTransferCondition.setOrderId(1802654988698693634L);
        return responseHelper.success(orderTransferService.list4GroupByOrderLimitOne(orderTransferCondition));
    }

    @PostMapping("/test")
    public ResponseMessage<Massagist> test(Long shopId, String date) throws Exception {
        LocalDateTime localDateTime = LocalDateTime.parse(date,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return responseHelper.success(memberOrderApplicationService.getRealMassagist(shopId, OrderUtils.toDate(localDateTime), new HashSet<>()));
    }

    @PostMapping("/queryProfit")
    public ResponseMessage<String> queryProfit(String beginDate, String endDate) throws Exception {
        List<Profit> profits = profitService.queryProfit(beginDate, endDate);
        int income = 0;
        if (CollUtil.isNotEmpty(profits)) {
            income = profits.stream()
                    .mapToInt(profit -> ObjectUtil.defaultIfNull(profit.getAdminIncome(), 0)).sum();
        }
        LocalDateTime localDateTime = LocalDateTime.parse(beginDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String msg = localDateTime.toLocalDate().getMonthValue() + "月利润为：" + income/100 + "元";
        return responseHelper.success(msg);
    }

    /**
     * 平台的各项指标
     * 每个城市、某天、业绩、已完成多少、进行中多少、取消多少
     * 以创建时间为准
     * @return
     * @throws Exception
     */
    @PostMapping("/queryKpi")
    public ResponseMessage<String> queryKpi(String beginDate, String endDate) throws Exception {
        CitiesServedCondition citiesServedCondition = new CitiesServedCondition();
        citiesServedCondition.setStatus(10);
        List<CitiesServed> citiesServedList = citiesServedService.listInfo(citiesServedCondition);
        StringBuilder sb = new StringBuilder();
        OrderInfoCondition condition = new OrderInfoCondition();
        condition.setBeginDate(beginDate);
        condition.setEndDate(endDate);
        List<OrderInfo> orderInfoList = orderService.orderList(condition);
        int todayPrice = 0;
        int extTotalPrice = 0;
        if (CollUtil.isNotEmpty(orderInfoList)) {
            todayPrice = orderInfoList.stream().filter(orderInfo -> orderInfo.getStatus()==40 || orderInfo.getStatus()==30).mapToInt(info -> ObjectUtil.defaultIfNull(info.getOrderPrice(), 0)).sum();
            extTotalPrice = orderInfoList.stream().filter(orderInfo -> orderInfo.getStatus()==40 || orderInfo.getStatus()==30).mapToInt(info -> ObjectUtil.defaultIfNull(info.getExtTotalPrice(), 0)).sum();
        }
        long ready = orderInfoList.stream().filter(orderInfo -> orderInfo.getStatus()==40).count();
        long ing = orderInfoList.stream().filter(orderInfo -> orderInfo.getStatus()==30).count();
        long cancel = orderInfoList.stream().filter(orderInfo -> orderInfo.getStatus()==99).count();
        LocalDateTime localDateTime = LocalDateTime.parse(beginDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String msg = localDateTime.toLocalDate() + " 平台数据---业绩：" + (todayPrice + extTotalPrice)/100 + "元，已完成：" + ready + "单，进行中：" + ing + "单，已取消：" + cancel + "单";
        sb.append(msg);
        citiesServedList.forEach(citiesServed -> {
            List<Shop> shop = shopService.getShopByCitiesId(citiesServed.getId());
            OrderInfoCondition condition0 = new OrderInfoCondition();
            condition0.setBeginDate(beginDate);
            condition0.setEndDate(endDate);
            if (CollUtil.isNotEmpty(shop)) {
                condition0.setShopIds(shop.stream().map(Shop::getId).toList());
            }
            List<OrderInfo> orderInfoList0 = orderService.orderList(condition0);
            int todayPrice0 = 0;
            int extTotalPrice0 = 0;
            if (CollUtil.isNotEmpty(orderInfoList0)) {
                todayPrice0 = orderInfoList0.stream().filter(orderInfo -> orderInfo.getStatus()==40 || orderInfo.getStatus()==30).mapToInt(info -> ObjectUtil.defaultIfNull(info.getOrderPrice(), 0)).sum();
                extTotalPrice0 = orderInfoList0.stream().filter(orderInfo -> orderInfo.getStatus()==40 || orderInfo.getStatus()==30).mapToInt(info -> ObjectUtil.defaultIfNull(info.getExtTotalPrice(), 0)).sum();
            }
            long ready0 = orderInfoList0.stream().filter(orderInfo -> orderInfo.getStatus()==40).count();
            long ing0 = orderInfoList0.stream().filter(orderInfo -> orderInfo.getStatus()==30).count();
            long cancel0 = orderInfoList0.stream().filter(orderInfo -> orderInfo.getStatus()==99).count();

            String msg0 = " " + citiesServed.getCityName() + "数据---业绩：" + (todayPrice0 + extTotalPrice0)/100 + "元，已完成：" + ready0 + "单，进行中：" + ing0 + "单，已取消：" + cancel0 + "单";
            sb.append(msg0);
        });
        return responseHelper.success(sb.toString());
    }

    @PostMapping("/queryShopKpi")
    public ResponseMessage<Kpi> queryShopKpi(long shopId) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setShopId(shopId);
        //获取门店业绩
        int perf = shopService.getShopPerf(orderInfo);
        //获取门店加钟率
        double extraRatio = shopService.getShopExtraRatio(shopId);
        //获取门店好评率
        double positiveRatio = shopService.getShopPositiveRatio(shopId);
        Kpi kpi = Kpi.builder()
                .extraRatio(extraRatio)
                .perf(perf)
                .positiveRatio(positiveRatio)
                .build();
        return responseHelper.success(kpi);
    }

    @PostMapping("/queryMassagistKpi")
    public ResponseMessage<Kpi> queryMassagistKpi(long massagistId) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setMassagistId(massagistId);
        //获取技师业绩
        int perf = massagistService.getMassagistPerf(orderInfo);
        //获取技师加钟率
        double extraRatio = massagistService.getMassagistExtraRatio(massagistId);
        //获取技师好评率
        double positiveRatio = massagistService.getMassagistPositiveRatio(massagistId);
        Kpi kpi = Kpi.builder()
                .extraRatio(extraRatio)
                .perf(perf)
                .positiveRatio(positiveRatio)
                .build();
        return responseHelper.success(kpi);
    }

    @Builder
    @Data
    public static class Kpi {

        private int perf;

        private double extraRatio;

        private double positiveRatio;
    }

}
